package com.xiaochen.log.aspect;

import com.xiaochen.log.annotation.Log;
import com.xiaochen.log.service.AsyncOperLogService;
import com.xiaochen.log.utils.LogUtil;
import com.xiaochen.model.entity.system.SysOperLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private AsyncOperLogService asyncOperLogService;


    // 环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){
//        String title = sysLog.title();
//        int businessType = sysLog.businessType();
//        System.out.println("title///"+title+"///businessType///"+businessType);

        // 业务方法调用之前,封装数据
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog, joinPoint, sysOperLog);

        // 业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            // 调用业务方法之后,封装数据
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 0, null);
        } catch (Throwable e) {
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 1, e.getMessage());
            // 这个位置的异常必须要抛出,如果没有抛出来,是不会被外层事务(@Transactional)捕获的,会造成事物的失效
            throw new RuntimeException(e);
        }
        // 调用service方法把日志信息添加数据库里面
        asyncOperLogService.saveSysOperLog(sysOperLog);
        return proceed;
    }
}
